package sjsu.android;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ArrayAdapter;
import dbAdapter.CreateFoodData;
import dbAdapter.DailyInfoDBAdapter1;
import dbAdapter.FoodDBAdapter;
public class AdvCategory extends Activity {
	Food clview;
	FoodDBAdapter fd;
	String userId;
	static DailyInfoDBAdapter1 di;
	String categoryName;
	AlertDialog.Builder builder;
	// define  adapter and view as fields to be initialized later
	Button ok,cancel,save,cancel1;
	int bval = 0,sval =0,lval=0, totalCalConsumed = 0;
	Dialog dialog,calDialog;
	ListView blist = null;
	Cursor cursor;
	String item;
	String[] breakfastItems,lunchItems,snackItems,dinnerItems,beveragesItems,dessertItems;
	private ListView llist = null;
	private ListView slist = null;
	private ListView dlist = null;
	private ListView delist = null;
	private ListView deslist = null;
	private ArrayAdapter<String> badapter = null;
	private ArrayAdapter<String> ladapter = null;
	private ArrayAdapter<String> sadapter = null;
	private ArrayAdapter<String> dadapter = null;
	private ArrayAdapter<String> deadapter = null;
	private ArrayAdapter<String> desadapter = null;
	EditText text2;
	int year ;
	int month;
	int day;
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.adv_cat);
		Intent myIntent = getIntent(); // this is just for example purpose
		userId = myIntent.getStringExtra("id");
		Bundle bun = getIntent().getExtras();
		month = bun.getInt("monthVal");
		day = bun.getInt("dayVal");
		year = bun.getInt("yearVal");
		System.out.println("Date fields from Advanced " +month +day +year);
		final Button button = (Button) findViewById(R.id.SearchButton);
		FoodDBAdapter nutritionDbAdapter = new FoodDBAdapter(AdvCategory.this);
		nutritionDbAdapter.open();
		String[] foodNames = nutritionDbAdapter.retrieveAllFoodNamesAsStringArray();		
		nutritionDbAdapter.close();
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				R.layout.search_suggestion_list_item, foodNames);

		final AutoCompleteTextView editText = (AutoCompleteTextView) findViewById(R.id.EditText01);
		editText.setAdapter(adapter);
		editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_NULL) {
					button.performClick();
				}
				return false;
			}
		});

		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// Perform action on click
				//final ListView listView = (ListView) findViewById(R.id.ListView01);
				//ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(HelloAndroid.this, R.layout.list_items, new String[] {"INdia", "China"});
				//listView.setAdapter(arrayAdapter);
				String query = editText.getText().toString();
				Log.v("HelloAndroid", "SearchQuery for " + query);


				final FoodDBAdapter nutritionDbAdapter = new FoodDBAdapter(AdvCategory.this);
				nutritionDbAdapter.open();
				final Cursor cursor = nutritionDbAdapter.fetchNutritionWithLike(query);
				if (cursor.getCount() == 0) {
					AlertDialog.Builder ab=new AlertDialog.Builder(AdvCategory.this);
					ab.setMessage("No Results Found");
				} else if (cursor.getCount() == 1) {
					cursor.moveToFirst();
					item = cursor.getString(cursor.getColumnIndex(FoodDBAdapter.KEY_NAME));
					categoryName = cursor.getString(cursor.getColumnIndex(FoodDBAdapter.KEY_CATEGORY));
					final String[] servings = {"One", "Two", "Three", "Four"};
					builder = new AlertDialog.Builder(AdvCategory.this);
					builder.setTitle("Choose number of servings");
					builder.setSingleChoiceItems(servings, -1, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int position) {
							if(position == 0){
								calcServings(categoryName,item,position);
							}
							else if (position == 1){
								calcServings(categoryName,item,position);
							}
							else if(position == 2){
								calcServings(categoryName,item,position);
							}
							else if(position == 3){
								calcServings(categoryName,item,position);
							}
						}
					});

					builder.show();

				} 
				else {

					/*
							SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(AdvCateg.this,
									R.layout.list_items, cursor, 
									new String[] {FoodDBAdapter.KEY_NAME},
									new int[] {R.id.TextViewNutritionName});
							listView.setAdapter(simpleCursorAdapter);
							//cursor.close();
							nutritionDbAdapter.close();
							listView.setOnItemClickListener(new OnItemClickListener() {

								public void onItemClick(AdapterView<?> arg0, View arg1,
										int position, long rowId) {

									Cursor c = (Cursor) listView.getItemAtPosition(position);
									Log.v("HelloAndroid", "" + c.getString(c.getColumnIndex(FoodDBAdapter.KEY_NAME)));
									String foodName = c.getString(c.getColumnIndex(FoodDBAdapter.KEY_NAME));
									Intent intent = new Intent(SearchActivity.this, NutritionInfo.class);
									intent.putExtra("itemName", foodName);
									startActivity(intent);
								}

							});
					 */

					AlertDialog.Builder ab=new AlertDialog.Builder(AdvCategory.this);
					ab.setCursor(cursor, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							if(cursor.moveToPosition(whichButton)){

								item = cursor.getString(cursor.getColumnIndex(FoodDBAdapter.KEY_NAME));
								categoryName = cursor.getString(cursor.getColumnIndex(FoodDBAdapter.KEY_CATEGORY));
								final String[] servings = {"One", "Two", "Three", "Four"};
								builder = new AlertDialog.Builder(AdvCategory.this);
								builder.setTitle("Choose number of servings");
								builder.setSingleChoiceItems(servings, -1, new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int position) {
										if(position == 0){
											calcServings(categoryName,item,position);
										}
										else if (position == 1){
											calcServings(categoryName,item,position);
										}
										else if(position == 2){
											calcServings(categoryName,item,position);
										}
										else if(position == 3){
											calcServings(categoryName,item,position);
										}
									}
								});

								builder.show();

							}
						}
					},FoodDBAdapter.KEY_NAME);
					ab.show();

				}
			}
		});


		CreateFoodData cf = new CreateFoodData();
		cf.create(this);
		fd = new FoodDBAdapter(this);
		fd.open();
		cursor = fd.fetchCategoryItems("Breakfast");
		breakfastItems = new String[cursor.getCount()];
		int i=0;
		while( cursor.moveToNext()){

			breakfastItems[i] = cursor.getString(1);
			System.out.println(breakfastItems[i]);
			i++;
		}

        cursor.close();
		fd.close();
		fd.open();
		cursor = fd.fetchCategoryItems("Lunch");
		lunchItems = new String[cursor.getCount()];
		int j=0;
		while( cursor.moveToNext()){

			lunchItems[j] = cursor.getString(1);
			System.out.println(lunchItems[j]);
			j++;
		}

		cursor.close();
		fd.close();
		fd.open();
		cursor = fd.fetchCategoryItems("Snack");
		snackItems = new String[cursor.getCount()];
		int k=0;
		while( cursor.moveToNext()){

			snackItems[k] = cursor.getString(1);
			System.out.println(snackItems[k]);
			k++;
		}

		cursor.close();
		fd.close();
		fd.open();
		cursor = fd.fetchCategoryItems("Dinner");
		dinnerItems = new String[cursor.getCount()];
		int l=0;
		while( cursor.moveToNext()){

			dinnerItems[l] = cursor.getString(1);
			System.out.println(dinnerItems[l]);
			l++;
		}

		cursor.close();
		fd.close();

		fd.open();
		cursor = fd.fetchCategoryItems("Beverages");
		beveragesItems = new String[cursor.getCount()];
		int m=0;
		while( cursor.moveToNext()){

			beveragesItems[m] = cursor.getString(1);
			System.out.println(beveragesItems[m]);
			m++;
		}

		cursor.close();
		fd.close();
		fd.open();
		cursor = fd.fetchCategoryItems("Dessert");
		dessertItems = new String[cursor.getCount()];
		int n=0;
		while( cursor.moveToNext()){

			dessertItems[n] = cursor.getString(1);
			System.out.println(dessertItems[n]);
			n++;
		}

		cursor.close();
		fd.close();
		
		di = new DailyInfoDBAdapter1(this);
		try{

			// initialize the adapter with the ListView defined in dataview.xml
			// and the array of String items defined in code
			badapter = new ArrayAdapter<String>(this, R.layout.dataview, breakfastItems);
			ladapter = new ArrayAdapter<String>(this, R.layout.dataview2, lunchItems);
			sadapter = new ArrayAdapter<String>(this, R.layout.dataview3, snackItems);
			dadapter = new ArrayAdapter<String>(this, R.layout.dataview4, dinnerItems);
			deadapter = new ArrayAdapter<String>(this, R.layout.dataview5, beveragesItems);
			desadapter = new ArrayAdapter<String>(this, R.layout.dataview6, dessertItems);

			// initializing the list from main.xml
			blist = (ListView) this.findViewById(R.id.ListView01);
			// getting the list view to use this adapter
			blist.setAdapter(badapter);   
			llist =(ListView) this.findViewById(R.id.ListView02);
			// getting the list view to use this adapter
			llist.setAdapter(ladapter);  
			slist = (ListView) this.findViewById(R.id.ListView03);
			// getting the list view to use this adapter
			slist.setAdapter(sadapter);   
			dlist = (ListView) this.findViewById(R.id.ListView04);
			// getting the list view to use this adapter
			dlist.setAdapter(dadapter);   
			delist = (ListView) this.findViewById(R.id.ListView05);
			// getting the list view to use this adapter
			delist.setAdapter(deadapter); 
			deslist = (ListView) this.findViewById(R.id.ListView06);
			// getting the list view to use this adapter
			deslist.setAdapter(desadapter);  

			blist.setOnItemClickListener(new ListItemSelectedHandler());
			llist.setOnItemClickListener(new ListItemSelectedHandler());
			slist.setOnItemClickListener(new ListItemSelectedHandler());
			dlist.setOnItemClickListener(new ListItemSelectedHandler());
			delist.setOnItemClickListener(new ListItemSelectedHandler());
			deslist.setOnItemClickListener(new ListItemSelectedHandler());

		}catch (Exception e){}

	}

	private class ListItemSelectedHandler implements AdapterView.OnItemClickListener
	{
		public void onItemClick(AdapterView<?> adapt, View view, int position, long id)
		{
			TextView text1,text3;
			Object obj = adapt.getAdapter();
			if(obj == badapter){
				categoryName = "Breakfast";
				item = breakfastItems[position];
				final String[] servings = {"One", "Two", "Three", "Four"};
				builder = new AlertDialog.Builder(AdvCategory.this);
				builder.setTitle("Choose number of servings");
				builder.setSingleChoiceItems(servings, -1, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int position) {
						if(position == 0){
							calcServings(categoryName,item,position);
						}
						else if (position == 1){
							calcServings(categoryName,item,position);
						}
						else if(position == 2){
							calcServings(categoryName,item,position);
						}
						else if(position == 3){
							calcServings(categoryName,item,position);
						}
					}
				});

				builder.show();
			}
			else if (obj == ladapter){
				categoryName = "Lunch";
				item = lunchItems[position];
				final String[] servings = {"One", "Two", "Three", "Four"};
				builder = new AlertDialog.Builder(AdvCategory.this);
				builder.setTitle("Choose number of servings");
				builder.setSingleChoiceItems(servings, -1, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int position) {
						if(position == 0){
							calcServings(categoryName,item,position);
						}
						else if (position == 1){
							calcServings(categoryName,item,position);
						}
						else if(position == 2){
							calcServings(categoryName,item,position);
						}
						else if(position == 3){
							calcServings(categoryName,item,position);
						}
					}
				});

				builder.show();

			}
			else if (obj == sadapter){
				categoryName = "Snack";
				item = snackItems[position];
				final String[] servings = {"One", "Two", "Three", "Four"};
				builder = new AlertDialog.Builder(AdvCategory.this);
				builder.setTitle("Choose number of servings");
				builder.setSingleChoiceItems(servings, -1, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int position) {
						if(position == 0){
							calcServings(categoryName,item,position);
						}
						else if (position == 1){
							calcServings(categoryName,item,position);
						}
						else if(position == 2){
							calcServings(categoryName,item,position);
						}
						else if(position == 3){
							calcServings(categoryName,item,position);
						}
					}
				});
				builder.show();
			}
			else if (obj == dadapter){
				categoryName = "Dinner";
				item = dinnerItems[position];
				final String[] servings = {"One", "Two", "Three", "Four"};
				builder = new AlertDialog.Builder(AdvCategory.this);
				builder.setTitle("Choose number of servings");
				builder.setSingleChoiceItems(servings, -1, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int position) {
						if(position == 0){
							calcServings(categoryName,item,position);
						}
						else if (position == 1){
							calcServings(categoryName,item,position);
						}
						else if(position == 2){
							calcServings(categoryName,item,position);
						}
						else if(position == 3){
							calcServings(categoryName,item,position);
						}
					}
				});
				builder.show();
			}
			else if (obj == deadapter){
				categoryName = "Beverages";
				item = beveragesItems[position];
				final String[] servings = {"One", "Two", "Three", "Four"};
				builder = new AlertDialog.Builder(AdvCategory.this);
				builder.setTitle("Choose number of servings");
				builder.setSingleChoiceItems(servings, -1, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int position) {
						if(position == 0){
							calcServings(categoryName,item,position);
						}
						else if (position == 1){
							calcServings(categoryName,item,position);
						}
						else if(position == 2){
							calcServings(categoryName,item,position);
						}
						else if(position == 3){
							calcServings(categoryName,item,position);
						}
						//	         Toast.makeText(getApplicationContext(), servings[item], Toast.LENGTH_SHORT).show();
					}
				});

				builder.show();
			}
			else if (obj == desadapter){
				categoryName = "Dessert";
				item = dinnerItems[position];
				final String[] servings = {"One", "Two", "Three", "Four"};
				builder = new AlertDialog.Builder(AdvCategory.this);
				builder.setTitle("Choose number of servings");
				builder.setSingleChoiceItems(servings, -1, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int position) {
						if(position == 0){
							calcServings(categoryName,item,position);
						}
						else if (position == 1){
							calcServings(categoryName,item,position);
						}
						else if(position == 2){
							calcServings(categoryName,item,position);
						}
						else if(position == 3){
							calcServings(categoryName,item,position);
						}
						//	         Toast.makeText(getApplicationContext(), servings[item], Toast.LENGTH_SHORT).show();
					}
				});
				builder.show();


			}
		}		
	}

	public void calcServings(String catname, String itemname,int qty){
		qty++;
		//	builder.
		//    clview = new CustomListView();
		fd.open();
		cursor = fd.fetchCalories(itemname);
		String[] Items = new String[cursor.getCount()];
		int m=0;
		while( cursor.moveToNext()){

			Items[m] = cursor.getString(1);
			System.out.println(Items[m]);
			m++;
		}
		int Cal = Integer.parseInt(Items[0]);
		System.out.println(Cal);
		totalCalConsumed = Cal * (qty);
		System.out.println(totalCalConsumed);
		insertIntoDB(totalCalConsumed);
		fd.close();
		clview = new Food();
		updateCalInProgressBar(clview);
		updateMyIntake( clview );
		System.out.println("Before sec intent");
		//			int myId = Integer.parseInt(userId);
		Intent intent = new Intent(AdvCategory.this, AdvCategory.class);
		intent.putExtra("id",userId);
		startActivity(intent);


	}

	public  void updateCalInProgressBar(Food clview){
		//        		    clview = new CustomListView();
		clview.updateProgressBar(month,day,year);

	}

	public void updateMyIntake(Food clview){
		try{
			System.out.println("At updateMyIntake");	
			//        		clview = new CustomListView();
			//		clview.setExpandableList();
			clview.simpleExpandable();
			System.out.println("At one");
			clview.updateWhatIAte();
		}catch(Exception ex){
			System.out.println(ex.getMessage());

		}

	}

	/*       	class  clicker implements Button.OnClickListener {              
            	public void onClick(View v) {
            		if(v == ok){
            			String qty = text2.getText().toString();
            			fd.open();
            			cursor = fd.fetchCalories(item);
            			String[] Items = new String[cursor.getCount()];
            			int m=0;
            			while( cursor.moveToNext()){

            				Items[m] = cursor.getString(1);
            				System.out.println(Items[m]);
            				m++;
            			}
            			int Cal = Integer.parseInt(Items[0]);
            			System.out.println(Cal);
            			totalCalConsumed = Cal * Integer.parseInt(qty);
            			System.out.println(totalCalConsumed);
            			calDialog = new Dialog(AdvCategory.this);

		                calDialog.setContentView(R.layout.caldialog);

		                calDialog.setTitle("Calories consumed..");

		                calDialog.setCancelable(true);

		                TextView text = (TextView) calDialog.findViewById(R.id.TextView01);

		                text.setText(Integer.toString(totalCalConsumed));
		                 save = (Button) calDialog.findViewById(R.id.Button01);
		                 cancel1 = (Button) calDialog.findViewById(R.id.Button02);
		                save.setOnClickListener(new clicker1());
		                cancel1.setOnClickListener(new clicker1());	
		                calDialog.show();
            		}
            		else if(v == cancel){

		                dialog.cancel();            			
            		}

            	}

        	}

        	class  clicker1 implements Button.OnClickListener {              
            	public void onClick(View v) {
            		if(v == save){
            			//save totalCalConsumed to DailyInfo;
            			insertIntoDB(totalCalConsumed);
            			calDialog.cancel();   
            			dialog.cancel();
            		}
            		else if(v == cancel1){

		                calDialog.cancel();            			
            		}
            	}}
	 */	
	public  void insertIntoDB(int caloriesConsumed) {
		int mYear;
		int mMonth;
		int mDay;
		String cal_burned = "0";
		String calConsumed, userIdString;
		di.open();    
		long idl;
		Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		System.out.println("day,month,year " +mYear +mDay +mYear);
		Date date = convertStringToDate(mDay, mMonth+1, mYear);
		calConsumed = new Integer(caloriesConsumed).toString();
		//	        userIdString = new Integer(id).toString();
		idl = di.insertUserInfo(
				userId,
				categoryName,
				item,
				calConsumed,//Calories_consumed
				cal_burned,
				date); 
		di.close();
	}

	public static Date convertStringToDate(int date, int month, int year){

		SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
		Date theDate = null;
		String in = date + "/" + month + "/" + year;
		try {
			theDate = dateFormat.parse(in); 
			return theDate;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return theDate;

	}

}

